import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { trpc } from '../utils/trpc'
import { useToast } from 'vue-toastification'

// 用户类型定义
export interface User {
  id: number
  email: string
  username: string
  role: 'ADMIN' | 'SUB_ADMIN' | 'USER'
  isActive: boolean
  avatar?: string
  lastLoginAt?: string
  createdAt: string
  createdByAdminId?: number | null
}

// 登录请求类型
export interface LoginRequest {
  email: string
  password: string
}

// 注册请求类型
export interface RegisterRequest {
  email: string
  username: string
  password: string
}

export const useAuthStore = defineStore('auth', () => {
  // 状态
  const user = ref<User | null>(null)
  const token = ref<string | null>(null)
  const isLoading = ref(false)
  const error = ref<string | null>(null)

  // 计算属性
  const isAuthenticated = computed(() => !!user.value && !!token.value)
  const isAdmin = computed(() => user.value?.role === 'ADMIN')
  const isSubAdmin = computed(() => user.value?.role === 'SUB_ADMIN')
  const hasAdminAccess = computed(() => isAdmin.value || isSubAdmin.value)

  // Toast通知
  const toast = useToast()

  // 初始化认证状态
  function initAuth() {
    const savedToken = localStorage.getItem('auth_token')
    const savedUser = localStorage.getItem('auth_user')

    if (savedToken && savedUser) {
      try {
        token.value = savedToken
        user.value = JSON.parse(savedUser)
      } catch (error) {
        // 如果解析失败，清除无效数据
        clearAuth()
      }
    }
  }

  // 保存认证信息
  function saveAuth(authToken: string, userData: User) {
    token.value = authToken
    user.value = userData
    localStorage.setItem('auth_token', authToken)
    localStorage.setItem('auth_user', JSON.stringify(userData))
  }

  // 清除认证信息
  function clearAuth() {
    token.value = null
    user.value = null
    localStorage.removeItem('auth_token')
    localStorage.removeItem('auth_user')
  }

  // 登录
  async function login(credentials: LoginRequest) {
    isLoading.value = true
    error.value = null

    try {
      const result = await trpc.auth.login.mutate(credentials)

      if (result.success && result.data) {
        saveAuth(result.data.token, result.data.user)
        toast.success(result.message || 'Login successful')
        return result.data
      } else {
        throw new Error(result.message || 'Login failed')
      }
    } catch (err: any) {
      error.value = err.message || 'Login failed'
      toast.error(error.value)
      throw err
    } finally {
      isLoading.value = false
    }
  }

  // 注册
  async function register(userData: RegisterRequest) {
    isLoading.value = true
    error.value = null

    try {
      const result = await trpc.auth.register.mutate(userData)

      if (result.success && result.data) {
        saveAuth(result.data.token, result.data.user)
        toast.success(result.message || 'Registration successful')
        return result.data
      } else {
        throw new Error(result.message || 'Registration failed')
      }
    } catch (err: any) {
      error.value = err.message || 'Registration failed'
      toast.error(error.value)
      throw err
    } finally {
      isLoading.value = false
    }
  }

  // 登出
  async function logout() {
    try {
      await trpc.auth.logout.mutate()
    } catch (error) {
      // 即使服务端登出失败，也要清除本地状态
      console.warn('Server logout failed:', error)
    } finally {
      clearAuth()
      error.value = null
      toast.success('Logged out successfully')
    }
  }

  // 获取用户资料
  async function fetchProfile() {
    if (!isAuthenticated.value) {
      return
    }

    isLoading.value = true
    error.value = null

    try {
      const result = await trpc.user.getProfile.query()

      if (result.success && result.data) {
        user.value = result.data
        // 更新本地存储
        localStorage.setItem('auth_user', JSON.stringify(result.data))
        return result.data
      } else {
        throw new Error(result.message || 'Failed to fetch profile')
      }
    } catch (err: any) {
      error.value = err.message || 'Failed to fetch profile'
      // 如果 token 无效，清除认证信息
      if (err.message?.includes('UNAUTHORIZED')) {
        clearAuth()
      }
      throw err
    } finally {
      isLoading.value = false
    }
  }

  // 修改密码
  async function changePassword(oldPassword: string, newPassword: string) {
    isLoading.value = true
    error.value = null

    try {
      const result = await trpc.auth.changePassword.mutate({
        oldPassword,
        newPassword
      })

      if (result.success) {
        toast.success(result.message || 'Password changed successfully')
        return true
      } else {
        throw new Error(result.message || 'Failed to change password')
      }
    } catch (err: any) {
      error.value = err.message || 'Failed to change password'
      toast.error(error.value)
      throw err
    } finally {
      isLoading.value = false
    }
  }

  // 清除错误
  function clearError() {
    error.value = null
  }

  // 初始化时恢复认证状态
  initAuth()

  return {
    // 状态
    user,
    token,
    isLoading,
    error,
    isAuthenticated,
    isAdmin,
    isSubAdmin,
    hasAdminAccess,

    // 方法
    login,
    register,
    logout,
    fetchProfile,
    changePassword,
    clearError,
    clearAuth,
    initAuth,
  }
})
